package com.xbongbong.paas.help;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.VisibleTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.VisibleRulePoJo;
import com.xbongbong.paas.pojo.dto.CoUserListDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateBatchDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.enums.errorcodes.ProErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;

/**
 * @author 吴峰
 * @date 2022/11/17 15:07
 */
@Component
public class BatchEditHelp {
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    /**
     * 校验编辑权限
     * @param fieldAttrEntityList
     * @param formDataUpdateBatchDTO
     * @param list
     * @throws XbbException
     */
    public void checkEditPermission(List<FieldAttrEntity> fieldAttrEntityList, FormDataUpdateBatchDTO formDataUpdateBatchDTO, List<PaasFormDataEntityExt> list) throws XbbException {
        for (FieldAttrEntity item : fieldAttrEntityList) {
            Integer visible = item.getVisible() != null ? item.getVisible() : BasicConstant.NO_USE;
            if (!Objects.equals(BasicConstant.IS_USE, visible)) {
                throw new XbbException(ProErrorCodeEnum.API_ERROR_260015);
            }
            Integer editable = item.getEditable() != null ? item.getEditable() : BasicConstant.NO_USE;
            if (!Objects.equals(BasicConstant.IS_USE, editable)) {
                throw new XbbException(ProErrorCodeEnum.API_ERROR_260015);
            }
        }
        if (CollectionsUtil.isEmpty(list)) {
            return;
        }
        List<Long> dataIdList = formDataUpdateBatchDTO.getDataIdList();
        String corpid = formDataUpdateBatchDTO.getCorpid();
        Integer businessType = formDataUpdateBatchDTO.getBusinessType();
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Boolean hasTeam = UserTeamEnum.hasTeam(businessType);
        boolean publicFlag = false;
        if (hasTeam) {
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                // 因为公海客户列表页的批量编辑，只要拿一个数据就能判断是否公海
                Integer isPublic = getIntegerOrDefaultFromFormData(list.get(0).getData(), CustomerManagementEnum.IS_PUBLIC.getAttr(), 0);
                publicFlag = isPublic == 1 ? true : false;
            }
            if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                // 因为公海客户列表页的批量编辑，只要拿一个数据就能判断是否公海
                Integer isPublic = getIntegerOrDefaultFromFormData(list.get(0).getData(), ClueEnum.IS_PUBLIC.getAttr(), 0);
                publicFlag = isPublic == 1 ? true : false;
            }
            formDataFormExplainHelper.getUserIdMap(dataIdList, corpid, businessType, publicFlag, mainUserMap, coUserMap);
        } else {
            CoUserListDTO coUserListDTO = new CoUserListDTO();
            BeanUtil.copyProperties(formDataUpdateBatchDTO, coUserListDTO);
            coUserListDTO.setFormDataIdIn(dataIdList);
            coUserMap = formDataFormExplainHelper.coUserMap(coUserListDTO);
        }


        for (FieldAttrEntity fieldAttrEntity : fieldAttrEntityList) {
            Integer visibleAdvance = fieldAttrEntity.getVisibleScopeEnable();
            Integer editAdvance = fieldAttrEntity.getEditableAdvanceEnable();

            if(Objects.equals(BasicConstant.IS_USE, visibleAdvance) || Objects.equals(BasicConstant.IS_USE, editAdvance)) {

                List<PaasFormDataEntityExt> noEditList = new ArrayList<>();
                List<PaasFormDataEntityExt> invisibleList = new ArrayList<>();
                for (PaasFormDataEntityExt formData: list) {
                    // 负责人，协同人
                    List<String> mainUserList = mainUserMap.get(formData.getId());
                    List<String> coUserList = coUserMap.get(formData.getId());

                    HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                    handlerExplainDTO.setUserId(formDataUpdateBatchDTO.getUserId());
                    handlerExplainDTO.setLoginUser(formDataUpdateBatchDTO.getLoginUser());
                    handlerExplainDTO.setCreatorId(formData.getCreatorId());
                    // 设置创建人
                    if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
                        handlerExplainDTO.setCreatorId(formData.getData().getString(CustomerManagementEnum.CREATOR.getAttr()));
                    } else {
                        handlerExplainDTO.setCreatorId(formData.getCreatorId());
                    }
                    if(hasTeam) {
                        handlerExplainDTO.setOwnerId(mainUserList);
                    } else {
                        handlerExplainDTO.setOwnerId(Collections.singletonList(formData.getOwnerId()));
                    }
                    if(coUserList != null && !coUserList.isEmpty()) {
                        handlerExplainDTO.setCoUserId(coUserList);
                    }

                    VisibleRulePoJo visibleRulePojo = fieldAttrEntity.getVisibleScopeRule();
                    if(Objects.equals(BasicConstant.IS_USE, visibleAdvance) && visibleRulePojo != null) {
                        Boolean invisible =  ExplainUtil.invisibleOfScope(fieldAttrEntity, handlerExplainDTO);
                        if (invisible) {
                            invisibleList.add(formData);
                        }
                    }
                    VisibleRulePoJo editRulePojo = fieldAttrEntity.getEditableRule();
                    if(Objects.equals(BasicConstant.IS_USE, editAdvance) && editRulePojo != null) {
                        Integer editType = editRulePojo.getType();
                        VisibleTypeEnum editTypeEnum = VisibleTypeEnum.getByType(editType);
                        switch (editTypeEnum) {
                            case NOT_SHOW_ANYONE:
                                if(ExplainUtil.notShowAnyOne(editRulePojo, handlerExplainDTO)) {
                                    noEditList.add(formData);
                                }
                                break;
                            case SOME_PEOPLE_CAN_SEE:
                                if(ExplainUtil.fieldCanSee(editRulePojo, handlerExplainDTO)) {
                                    noEditList.add(formData);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
                if(!invisibleList.isEmpty()) {
                    // 错误信息
                    throw new XbbException(ProErrorCodeEnum.API_ERROR_500018, String.format(ProErrorCodeEnum.API_ERROR_500018.getMsg(), invisibleList.size()));
                }
                if(!noEditList.isEmpty()) {
                    // 错误信息
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, String.format(ProErrorCodeEnum.API_ERROR_500018.getMsg(), noEditList.size()));
                }
            }
        }

    }
}
